﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using mozhi.smarterp.AuthorCenter.Users.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Guids;
using Volo.Abp.Identity;
using Volo.Abp.Settings;
using Volo.Abp.Threading;

namespace mozhi.smarterp.AuthorCenter.Users.Services
{
    public class CustomIdentityUserManager : IdentityUserManager
    {
        private IUserDataPermissionRepository _userDataPermissionRepository;
        private IGuidGenerator _guidGenerator;


        public CustomIdentityUserManager(IdentityUserStore store, IIdentityRoleRepository roleRepository, IIdentityUserRepository userRepository, IOptions<IdentityOptions> optionsAccessor,
            IPasswordHasher<IdentityUser> passwordHasher, IEnumerable<IUserValidator<IdentityUser>> userValidators, IEnumerable<IPasswordValidator<IdentityUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<IdentityUserManager> logger,
            ICancellationTokenProvider cancellationTokenProvider, IOrganizationUnitRepository organizationUnitRepository, ISettingProvider settingProvider , 
            IUserDataPermissionRepository userDataPermissionRepository , IGuidGenerator guidGenerator) : 
            base(store, roleRepository, userRepository, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, cancellationTokenProvider, organizationUnitRepository, settingProvider)
        {
            _userDataPermissionRepository = userDataPermissionRepository;
            _guidGenerator = guidGenerator;
        }

        public async Task UpdateUserDataPermissionAsync(IdentityUser user , bool isOwnDepartment , bool isOwnCrated)
        {
            var userDataPermission = await _userDataPermissionRepository.FindAsync(user.Id);

            if (userDataPermission == null)
            {
                userDataPermission = new UserDataPermission(_guidGenerator.Create(), user.Id, isOwnDepartment, isOwnCrated);
                await _userDataPermissionRepository.InsertAsync(userDataPermission);
            }
            else
            {
                userDataPermission.Change(isOwnDepartment, isOwnCrated);

                await _userDataPermissionRepository.UpdateAsync(userDataPermission);
            }   
        }
    }
}
